﻿
//

//



using System.Text.Json.Nodes;

namespace Admin.NET.Core.JsonMapping
{

    public static class JsonNodeExtensions
    {
        public static JsonNode? GetValueOrNull(this JsonNode? node, string path)
        {
            if (node == null || string.IsNullOrEmpty(path))
                return null;

            var parts = path.Split('.');
            JsonNode current = node;

            foreach (var part in parts)
            {
                if (part.Contains("["))
                {
                    // 处理数组索引：xxx[0]
                    var bracketIndex = part.IndexOf('[');
                    var propName = part.Substring(0, bracketIndex);
                    var indexStr = part.Substring(bracketIndex + 1, part.Length - bracketIndex - 2); // 去掉 [ 和 ]

                    if (!int.TryParse(indexStr, out int index))
                        return null;

                    if (current is not JsonObject obj ||
                        !obj.TryGetPropertyValue(propName, out var arrayNode) ||
                        arrayNode is not JsonArray arr ||
                        arr.Count <= index)
                    {
                        return null;
                    }

                    current = arr[index];
                }
                else
                {
                    // 普通属性访问
                    if (current is not JsonObject obj ||
                        !obj.TryGetPropertyValue(part, out current))
                    {
                        return null;
                    }
                }
            }

            return current;
        }

    }
}
